<?php
/**
 * Created by JetBrains PhpStorm.
 * User: khathirdstep1025
 * Date: 9/27/12
 * Time: 9:54 PM
 * To change this template use File | Settings | File Templates.
 */

class Cart_model extends CI_Model{

    public function retrieve_products($limit, $offset, $cat = 'PL002'){

        $query = $this->db->get_where('bh_product', array('category_id' => $cat), $limit, $offset);
        return $query->result_array();
    }

    public function validate_add_cart_item(){
        $id = $this->input->post('product_id');
        $qty = $this->input->post('quantity');
        $this->db->where('product_id', $id);
        $query = $this->db->get('product', 1);
        if ($query->num_rows > 0){
            foreach($query->result() as $row){
                $data = array(
                    'id' => $id,
                    'qty' => $qty,
                    'price' => $row->product_price,
                    'name' => $row->product_name,
                    'price_origin' => $row->product_price_origin,
                );

                $this->cart->insert($data);
                return TRUE;
            }

        } else {
            return FALSE;
        }
    }

    public function validate_update_cart() {
        // Get the total number of items in cart
        $total = $this->cart->total_items();
        echo $total;
        // Retrieve the posted information
        $item = $this->input->post('rowid');
        $qty = $this->input->post('qty');
        // Cycle true all items and update them
        for ($i = 0; $i < count($item); $i++) {
            // Create an array with the products rowid's and quantities.
            $data = array(
                'rowid' => $item[$i],
                'qty' => $qty[$i],
            );
            // Update the cart with the new information
            $this->cart->update($data);
        }
    }

    public function total_cart(){
        return $this->cart->total_items();
    }

    public function empty_cart(){
        $this->cart->destroy();
    }

    public function total_product(){
        return $query = $this->db->count_all('product');
    }

    public function total_product_category($cat = 'PL005'){
        $query = $this->db->get_where('product', array('category_id' => $cat));
        return $query->num_rows;
    }

    public function product_qty($id){
        $this->db->where('product_id', $id);
        $query = $this->db->get('product', 1);
        if ($query->num_rows > 0){
            foreach($query->result() as $row){
                if ($row->product_quantity == 0){
                    return "HET_HANG";
                }
            }

        } else {
            return FALSE;
        }
    }

}